package com.abe.libcore.utils.clickeffect;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;

import com.abe.libcore.utils.ThreadPoolUtils;


/**
 * 通过设置view的setOnTouchListener， 实现点击时变小一下松开时还原的效果
 */
@SuppressLint("ClickableViewAccessibility")
public class OnClickEffectTouchListener implements View.OnTouchListener {

    private boolean isInterceptTouch = false;
    private View view;

    class ViewHandler extends Handler {
        public ViewHandler(Looper looper) {
            super(looper);
        }

        public void handleMessage(Message msg) {
            mViewClickEffect.onUnPressedEffect(view);
            if (view.isPressed()) {
                view.performClick();
                view.setPressed(false);
            }
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        this.view = v;
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mViewClickEffect.onPressedEffect(v);
                v.setPressed(true);
                if (!isInterceptTouch) {
                    ThreadPoolUtils.INSTANCE.execute(new DelayChangePressedStaus());
                }
                break;
            case MotionEvent.ACTION_MOVE:
                float x = event.getX();
                float y = event.getY();
                boolean isInside = (x > 0 && x < v.getWidth() && y > 0 && y < v
                        .getHeight());
                if (v.isPressed() != isInside) {
                    v.setPressed(isInside);
                }
                break;
            case MotionEvent.ACTION_CANCEL:
                mViewClickEffect.onUnPressedEffect(v);
                v.setPressed(false);
                break;
            case MotionEvent.ACTION_UP:
                mViewClickEffect.onUnPressedEffect(v);
                if (v.isPressed()) {
                    v.performClick();
                    v.setPressed(false);
                }
                break;
        }
        return isInterceptTouch;
    }

    /**
     * 如果不拦截，启用延时弹起
     */
    class DelayChangePressedStaus implements Runnable {

        @Override
        public void run() {
            try {
                Thread.sleep(200);
                new ViewHandler(Looper.getMainLooper()).sendEmptyMessage(0x001);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * View的点击状态效果定义
     */
    private ViewClickEffect mViewClickEffect = new DefaultClickEffectScaleAnimate();

    public ViewClickEffect getViewClickEffect() {
        return mViewClickEffect;
    }

    public void setViewClickEffect(ViewClickEffect viewClickEffect) {
        mViewClickEffect = viewClickEffect;
    }
}
